const provide = Vue.provide;
const reactive = Vue.reactive;
const inject = Vue.inject;
const EventNameChangeCard = "EventNameChangeCard";
const EventNameTakeGift = "EventNameTakeGift";
// 生产环境
// const requestHost = `https://vgi.quliye.com`;
const env_prod = "";
// 开发环境自己搭建nginx做了一个代理服务器
const env_dev = "http://127.0.0.1:1988";

const requestHost = `${env_prod}/api_cloud_game`;
// 获取URI参数对象
const queryParse = (url) => {
  return Array.from(new URL(url).searchParams).reduce((cur, [key, value]) => {
    cur[key] = value;
    return cur;
  }, {});
};
const Popup = {
  template: "#popup",
  data() {
    return {
      title: "提示",
      // desc: '游戏条件未达成，请稍后再试',
      // desc: '福利稍后通过私信发放，请注意查收',
      desc: "",
      show: false,
    };
  },
  mounted() {
    MyEvent.on(EventNameTakeGift, this.setPopup);
  },
  methods: {
    setPopup(info = {}) {
      this.show = info.show || false;
      this.title = info.title || "提示";
      this.desc = info.desc || "";
    },
    onConfirm() {
      this.show = false;
      this.title = "提示";
      this.desc = "";
    },
  },
};
const GiftContent = {
  template: "#content-gift",
  props: {
    card: Object,
  },
  methods: {
    changeCard() {
      this.$copyText();
      MyEvent.emit(EventNameChangeCard, {
        isGetGift: true,
        _index_: this.card._index_,
      });
    },
  },
};
const StartGameBtn = {
  template: "#btn-start",
  props: {
    card: Object,
  },
  mounted() {
    // console.log('StartGameBtn this.card', this.card);
  },
};
const ShortContent = {
  template: "#content-short",
  props: {
    card: Object,
  },
  mounted() {
    // console.log('ShortContent this.card', this.card);
  },
};
const CardA = {
  template: "#card-a",
  props: {
    card: Object,
  },
  created() {},
  methods: {},
};
const CardB = {
  template: "#card-b",
  props: {
    card: Object,
  },
  created() {},
  methods: {},
};
const CardC = {
  template: "#card-c",
  props: {
    card: Object,
  },
  created() {},
  methods: {},
};
const App = {
  template: "#my-app",
  data() {
    return {
      cardDataList: [],
      popupInfo: {},
    };
  },
  mounted() {
    this.getInitData();
    this.postLogin();
    MyEvent.on(EventNameChangeCard, this.changeData);
  },
  methods: {
    postLogin() {
      /**
             *  
             * const CryptoJS = require('crypto-js')
             * var time = new Date().getTime();
                var key = 'b3ewi79c624r766dsq14o5296534849t';
                var basestr = 'game_uid=dsf3wfsfw3ff&timestamp='+time;
                var result =  CryptoJS.MD5(basestr+'&key='+key).toString();

                console.log("time",time);
                console.log("sign",result);
             */
      // const urlParams = queryParse(`${window.location.href}?uid=dsf3wfsfw3ff&time=1711630904154&sign=e875c59c23e3cfd58c929b0cc55891af`)
      const urlParams = queryParse(`${window.location.href}`);
      console.log(urlParams);
      if (
        !urlParams.game_uid ||
        !urlParams.is_verified ||
        !urlParams.timestamp ||
        !urlParams.sign
      ) {
        // showToast('用户信息有误')
        return;
      }
      MyXHR({
        url: `${requestHost}/index/weibo/login`,
        methed: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        data: {
          uid: urlParams.game_uid,
          verified: urlParams.is_verified,
          time: urlParams.timestamp,
          sign: urlParams.sign,
        },
      }).then((res) => {
        if (`${res.code}` === "100000") {
          sessionStorage.setItem("token", res.data.token || "");
        } else {
          showToast(res.msg || "请求出错,请稍后重试");
        }
      });
    },
    getInitData() {
      MyXHR({
        url: `./assets/js/data.json?r=${Math.random()}`,
      }).then((res) => {
        this.cardDataList = (res.data || []).map((item, index) => ({
          ...item,
          isGetGift: false,
          _index_: index,
        }));
      });
    },
    changeData(data) {
      const index = data._index_;
      this.cardDataList[index] = { ...this.cardDataList[index], ...data };
    },
    onTakeGift() {
      const token = sessionStorage.getItem("token");
      MyXHR({
        url: `${requestHost}/index/weibo/takeGift`,
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
      }).then((res) => {
        if (`${res.code}` === "100000") {
          this.popupInfo = {
            show: true,
            desc: res.msg,
          };
          MyEvent.emit(EventNameTakeGift, { ...this.popupInfo });
        } else {
          showToast(res.msg || "请求出错,请稍后重试");
        }
      });
    },
  },
};

const gotoGameAPP = (URL) => {
  window.location.href = URL;
};

const handleClipboard = (isShowTip = true) => {
  const clipboard = new ClipboardJS(".btn-copy");
  clipboard.on("success", (e) => {
    try {
      isShowTip && showToast("礼包已领取复制");
      clipboard.destroy();
      e && e.clearSelection && e.clearSelection();
    } catch (error) {
      console.log(error);
    }
  });
  clipboard.on("error", (e) => {
    try {
      isShowTip && showToast("复制出错");
      clipboard.destroy();
      e && e.clearSelection && e.clearSelection();
    } catch (error) {
      console.log(error);
    }
  });
};

function showToast(message) {
  var toastContainer = document.getElementById("toastContainer"); // 获取消息框元素
  toastContainer.textContent = message; // 设置消息框的内容为传入的消息
  toastContainer.style.opacity = 1; // 设置消息框的透明度为1，显示消息框
  setTimeout(function () {
    toastContainer.style.opacity = 0; // 3秒后，设置消息框的透明度为0，隐藏消息框
  }, 3000);
}
const components = {
  install: function (Vue) {
    Vue.component("carda", CardA);
    Vue.component("cardb", CardB);
    Vue.component("cardc", CardC);
    Vue.component("popup", Popup);
    Vue.component("shortcontent", ShortContent);
    Vue.component("startgamebtn", StartGameBtn);
    Vue.component("giftcontent", GiftContent);
    Vue.config.globalProperties.$gotoGameAPP = gotoGameAPP;
    Vue.config.globalProperties.$toast = showToast;
    Vue.config.globalProperties.$copyText = handleClipboard;
  },
};
var app = Vue.createApp(App).use(components).mount("#app");
